package com.dftdla.server.handler;

import com.alibaba.fastjson2.JSONObject;
import com.dftdla.dao.pojo.ChatGroup;
import com.dftdla.dao.pojo.UserGroup;
import com.dftdla.dao.service.ChatGroupService;
import com.dftdla.dao.service.UserGroupService;
import com.dftdla.result.ResponseResult;
import com.dftdla.server.message.request.GroupCreateRequestMessage;
import com.dftdla.server.session.Session;
import com.dftdla.util.Code;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;


/**
 * @author 14501
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {

    @Resource
    private ChatGroupService chatGroupService;
    @Resource
    private UserGroupService userGroupService;

    @Override
    @Transactional
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) {
        Long userId = msg.getUserId();

        //创建群组
        ChatGroup chatGroup = new ChatGroup();
        chatGroup.setGroupName(msg.getGroupName());
        chatGroupService.save(chatGroup);

        //将创建人拉入群组
        UserGroup userGroup = new UserGroup();
        userGroup.setGroupId(chatGroup.getId());
        userGroup.setUser(userId);
        userGroupService.save(userGroup);

        JSONObject object = new JSONObject();
        object.put("groupId",chatGroup.getId());
        object.put("groupName",chatGroup.getGroupName());

        ArrayList<Long> longs = new ArrayList<>();
        longs.add(userId);
        object.put("users",longs);

        ctx.writeAndFlush(new TextWebSocketFrame(new ResponseResult<>(Code.SUCCESS.code,object).toString()));
    }
}
